<?php
/**
 * Created by PhpStorm.
 * User: jiangxiaobo
 * Date: 2019/11/11 0011
 * Time: 19:01
 */
namespace bootstrap;

use bootstrap\lib\Request;
use bootstrap\lib\Response;
use routes\WebConfig;
use routes\ConsoleConfig;
use routes\ApiConfig;

final class App
{
    static public function autoload($classname)
    {
        /**
         * \app::a(); => $classname=app
         * \app\index::a(); => $classname=app\index
         */
        $names = explode("\\", $classname);

        $filename = ROOT_PATH.implode(DS, $names).EXT;

        include $filename;
    }

    static public function appShutdown()
    {
        if ($e = error_get_last()) {
            switch($e['type']){
                case E_ERROR:
                case E_PARSE:
                case E_CORE_ERROR:
                case E_COMPILE_ERROR:
                case E_USER_ERROR:
                    ob_end_clean();
                    break;
            }
        }
        // echo "app end";
        // 正常结束程序
        exit;
    }

    static public function appError($errNo, $errStr, $errFile, $errLine)
    {
        var_dump('appError',$errNo, $errStr, $errFile, $errLine);
    }

    static public function appException($e)
    {
        var_dump('appException',$e);
    }

    static public function main()
    {
        // 环境常量
        define('IS_CLI', PHP_SAPI == 'cli' ? true : false);
        define('IS_WIN', strpos(PHP_OS, 'WIN') !== false);

        define('EXT', '.php');
        define('DS', DIRECTORY_SEPARATOR);
        define('ROOT_PATH', dirname(dirname(realpath($_SERVER['SCRIPT_FILENAME']))) . DS);

        defined('ENV_PREFIX') or define('ENV_PREFIX', 'PHP_'); // 环境变量的配置前缀

        // 注册AUTOLOAD方法
        spl_autoload_register(__CLASS__."::autoload");

        // 当我们的脚本执行完成或意外死掉导致PHP执行即将关闭时,我们的这个函数将会被调用
        register_shutdown_function(__CLASS__."::appShutdown");
        // 设定错误和异常处理
        set_error_handler(__CLASS__."::appError");
        set_exception_handler(__CLASS__."::appException");

        if(IS_CLI) {
            ConsoleConfig::getInstance()->trigger();
        } else if(Request::getInstance()->isAjax()) {
            ApiConfig::getInstance()->trigger();
        } else {
            WebConfig::getInstance()->trigger();
        }

        return Response::getInstance();
    }
}
